package com.example.function.integration;

import com.example.function.integration.utils.CmdAutoStartRedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Description：功能集成服务启动类
 * @Author：fengcheng
 * @Date：2024/10/14 14:38
 */
@Slf4j
@MapperScan({"com.example.function.integration.mapper"})
@ImportResource("classpath:spring-config.xml")
@SpringBootApplication
@EnableScheduling
public class FunctionIntegrationApplication {

    public static void main(String[] args) {
        System.out.println();
        System.out.println();
        SpringApplication.run(FunctionIntegrationApplication.class, args);
        System.out.println();
        System.out.println();
        System.out.println("功能集成项目 FunctionIntegrationApplication 启动成功");
    }

    @PostConstruct
    public void PostConstruct() {
        log.info("系统启动前-----开始启动redis服务------------------");
        // 单起一个线程，用来启动redis服务
        new Thread(CmdAutoStartRedisUtils::startRedisService).start();
    }

    @PreDestroy
    public void PreDestroy() {
        log.info("系统停止前-----开始停止redis服务------------------");
        try {
            // 停止redis命令（全路径命令）
            String commandPath = "D:\\gong-zuo\\kai-fa-gong-ju\\redis\\install\\redis-cli shutdown";
            Process process = Runtime.getRuntime().exec(commandPath);
            // 读取命令执行结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            // 关闭流
            reader.close();
            // 等待命令执行完成
            int exitCode = process.waitFor();
            log.info("命令执行完成，退出码：" + exitCode);
        } catch (IOException | InterruptedException e) {
            log.error("停止redis服务失败", e);
        }
    }
}
